#include"Heap.h"




void HeapInit(HP* head)
{
	assert(head);
	head->a = (HPdatanode*)malloc(sizeof(HPdatanode));
	//head->a = NULL;
	head->capacity = 1;
	head->size = 0;
}
void HeapDestory(HP* head)
{
	assert(head);
	free(head->a);
	head->a = NULL;
	head->capacity = 0;
	head->size = 0;
}
void Heapchange(HPdatanode* x, HPdatanode* y)
{
	assert(x);
	assert(y);
	HPdatanode tmp = *x;
	*x = *y;
	*y = tmp;
}
void HangeHeap(HPdatanode* head, int chile)
{
	assert(head);
	int elder = (chile - 1) / 2;
	while (chile > 0)
	{
		if (head[chile] > head[elder])
		{
			/*HPdatanode tmp = head->a[chile];
			head->a[chile] = head->a[elder];
			head->a[elder] = tmp;*/
			Heapchange(&(head[chile]), &(head[elder]));
			chile = elder;
			elder = (chile - 1) / 2;
		}
		else
		{
			break;
		}
	}
}

void HeapPush(HP* head, HPdatanode x)
{
	assert(head);
	if (head->size == head->capacity)
	{
		HPdatanode* tmp = (HPdatanode*)realloc(head->a, sizeof(HPdatanode) * head->capacity * 2);
		if (tmp == NULL)
		{
			perror("realloc");
			return;
		}
		head->a = tmp;
		head->capacity = head->capacity * 2;
	}
	head->a[head->size] = x;
	head->size++;
	HangeHeap(head->a, head->size - 1);
	/*if (head->size == 1)
	{
		return;
	}*/
}
void headDown(int* head, int n, int parent)
{
	int child = (parent) * 2 + 1;
	while (child < n)
	{
		if (child + 1 < n && head[child] > head[child + 1])
		{
			child++;
		}
		if (head[child] < head[parent])
		{
			Heapchange(&(head[parent]), &(head[child]));
			parent = child;
			child = (parent) * 2 + 1;
		}
		else
		{
			return;
		}
	}
}
void HeapPop(HP* head)
{
	assert(head);
	Heapchange(&(head->a[0]), &(head->a[head->size - 1]));
	head->size--;
	headDown(head->a, head->size, 0);
	//int child = (parent) * 2 + 1;
	//while (child<n)
	//{
	//	if (child < head->size && head->a[child] > head->a[child+1])
	//	{
	//		child++;
	//	}
	//	if (child < head->size && head->a[parent] > head->a[child])
	//	{
	//		Heapchange(&(head->a[parent]), &(head->a[child]));
	//		parent = child;
	//		child = (parent) * 2 + 1;
	//	}
	//	else
	//	{
	//		return;
	//	}
	//}
}
HPdatanode HeapTop(HP* head)
{
	assert(head);
	HPdatanode tmp = head->a[0];
	return tmp;
}
bool HeapEmpty(HP* head)
{
	assert(head);
	return head->size == 0;
}